package com.rt.java.sql;

import java.sql.*;

public class JDBCDemo {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/demo?useSSL=false",
                    "root",
                    "jrbjrb811");
            connection.setAutoCommit(false); // 开启事务
            preparedStatement = connection.prepareStatement("select * from demo_student where stu_age > ?");
            preparedStatement.setInt(1, 18);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                System.out.println(resultSet.getString("stu_name") + " => " + resultSet.getInt("stu_age"));
            }
            connection.commit(); // 事务提交
        } catch (Exception e) {
            e.printStackTrace();
            connection.rollback(); // 事务回滚
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
